package com.sinosoft.content;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.sinosoft.base.Constants;
import com.sinosoft.base.GenericDaoHibernate;
import com.sinosoft.util.CheckEmpty;
import com.sinosoft.util.DateTimeUtils;

@Repository
public class ContentEnDaoHibernate extends GenericDaoHibernate<ContentEn, Long> implements ContentEnDao {

	public ContentEnDaoHibernate(){
		super(ContentEn.class);
	}

	/**
	 * 新增或修改content
	 */
	public ContentEn saveContent(ContentEn con){
		if (null == con.getContentId()) {
			getHibernateTemplate().save(con);
		} else {
			getHibernateTemplate().merge(con);
		}
		return con;
	}

	/**
	 * 根据id获取content
	 */
	public ContentEn getContentById(Long conId){
		List<ContentEn> list=getHibernateTemplate().find("from ContentEn where contentId=?",conId);
		if(null!=list&&list.size()>0){
			return list.get(0);
		}
		return null;
	}

	/**
	 * 获取所有Content
	 */
	public List<ContentEn> getAllContent(){
		return getHibernateTemplate().find("from ContentEn ");
	}

	/**
	 * 删除Content
	 */
	public void removeContentEn(ContentEn con) {
		getHibernateTemplate().delete(con);
	}
	
	/**
	 * 根据条件查询新闻信息
	 */
	public List<ContentEn> getContentByType(ContentView vo){
		List list=null;
		if(null==vo){
			return null;
		}
		Session session=null;
		try {
			session=getHibernateTemplate().getSessionFactory().openSession();
			Criteria c=session.createCriteria(ContentEn.class);
			if(!CheckEmpty.isEmpty(vo.getContentTitle())){
				c.add(Restrictions.like("contentTitle", "%"+vo.getContentTitle()+"%"));
			}
			if(null!=vo.getContentType()&&vo.getContentType()>0){
				c.add(Restrictions.eq("contentType",vo.getContentType()));
			}
			if(null!=vo.getIsRelease()&&vo.getIsRelease()>0){
				c.add(Restrictions.eq("isRelease", vo.getIsRelease()));
			}
			if(!CheckEmpty.isEmpty(vo.getStartime())){
				c.add(Restrictions.gt("contentTime", DateTimeUtils.StringToDate(vo.getStartime())));
			}
			if(!CheckEmpty.isEmpty(vo.getEndtime())){
				c.add(Restrictions.lt("contentTime", DateTimeUtils.StringToDate(vo.getEndtime())));
			}
			if(Constants.ORDER_DESC.equals(vo.getOrder())){
				c.addOrder(Order.desc("contentTime"));
			}else{
				c.addOrder(Order.asc("contentTime"));
			}
			if(vo.getBegin()>=0&&vo.getPageSize()>0){
				c.setFirstResult(vo.getBegin());
				c.setMaxResults(vo.getPageSize());
			}
			
			list=c.list();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}
}